<template>
  <div class="batch-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>评论批次列表</h2>
          <div class="header-actions">
<!--            <el-button-->
<!--                type="danger"-->
<!--                :disabled="!selectedBatchNos.length"-->
<!--                @click="handleEdit(null,true)"-->
<!--            >-->
<!--              修改基本信息-->
<!--            </el-button>-->
            <el-button
                type="primary"
                :disabled="!selectedBatchNos.length"
                @click="handleExport"
            >
              导出外链链接
            </el-button>
            <el-button
                type="success"
                :disabled="!selectedBatchNos.length"
                @click="handleDelete(null,true)"
            >
              删除选中项
            </el-button>
            <el-button
                type="danger"
                :disabled="!selectedBatchNos.length"
                @click="refresh(null,true)"
            >
              刷新进度
            </el-button>
          </div>
        </div>
      </template>

      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="batchList"
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
          border
          @selection-change="handleSelectionChange"
      >

        <!-- 选择列 -->
        <el-table-column type="selection" width="55">
          <template #header>
            <el-dropdown trigger="click" @command="handleSelectionCommand">
              <el-button type="text">
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="selectAll">全选</el-dropdown-item>
                  <el-dropdown-item command="unselectAll">取消全选</el-dropdown-item>
                  <el-dropdown-item command="invertSelection">反选</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column type="index" :index="getTableIndex" width="60" align="center" />
        <el-table-column prop="batchNo" label="批次号" width="180" >
          <template #default="{ row }">
            <div v-if="row.batchNo === ''">单任务，无批次号</div>
            <div v-else>{{row.batchNo}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" width="200">
          <template #default="{ row }">
            <el-progress
                :percentage="calculateProgress(row)"
                :status="getProgressStatus(row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column label="统计" min-width="150">
          <template #default="{ row }">
            <div class="flex items-center space-x-4">
              <el-statistic
                  title="总数"
                  :value="row.totalCount"
                  :value-style="{ fontSize: '14px' }"
              />
              <el-statistic
                  title="成功"
                  :value="row.successCount"
                  :value-style="{ fontSize: '14px', color: '#67C23A' }"
              />
              <el-statistic
                  title="失败"
                  :value="row.failureCount"
                  :value-style="{ fontSize: '14px', color: '#F56C6C' }"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="基本信息" min-width="180">
          <template #default="{ row }">
            <el-popover
                placement="top-start"
                title="评论信息"
                :width="300"
                trigger="hover"
            >
              <template #reference>
                <el-button link type="primary">查看信息</el-button>
              </template>
              <div class="space-y-2">
                <div><strong>昵称：</strong>{{ row.nickname }}</div>
                <div><strong>邮箱：</strong>{{ row.email }}</div>
                <div><strong>网站：</strong>{{ row.websiteUrl }}</div>
                <div>
                  <strong>评论内容：</strong>
                  <div class="mt-1 text-gray-600">{{ row.commentContent }}</div>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <!-- 修改操作列 -->
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                  type="primary"
                  link
                  @click="viewDetails(row.batchNo)"
              >
                查看详情
              </el-button>
<!--              <el-button-->
<!--                  type="primary"-->
<!--                  link-->
<!--                  @click="handleEdit(row)"-->
<!--              >-->
<!--                修改信息-->
<!--              </el-button>-->
              <el-button
                  type="danger"
                  link
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-button
                  type="success"
                  link
                  @click="refresh(row)"
              >
                刷新进度
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-between mt-4" style="margin-top: 5px;margin-bottom: 5px">
        <div class="text-gray-500" v-if="selectedBatchNos.length">
          已选择 {{ selectedBatchNos.length }} 项
          <el-button link type="primary" @click="handleSelectionCommand('unselectAll')">
            清空选择
          </el-button>
        </div>
        <div v-else></div>

        <div class="flex justify-end mt-4">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="isMultiple ? '批量修改基本信息' : '修改基本信息'"
        width="500px"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="editForm"
          :rules="formRules"
          label-width="100px"
      >
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="网站" prop="websiteUrl">
          <el-input v-model="editForm.websiteUrl" />
        </el-form-item>
        <el-form-item label="评论内容" prop="commentContent">
          <el-input
              v-model="editForm.commentContent"
              type="textarea"
              rows="4"
          />
        </el-form-item>

        <!-- 添加重新提交选项 -->
        <el-form-item>
          <el-checkbox v-model="editForm.resubmit">
            修改后重新提交评论
          </el-checkbox>
          <el-tooltip
              content="选中后将重置所有任务状态并重新发起评论"
              placement="right"
          >
            <el-icon class="ml-1"><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-form-item>

        <!-- 添加提示信息 -->
        <div v-if="editForm.resubmit" class="text-sm text-gray-500 mt-2 p-3 bg-gray-50 rounded">
          <el-icon class="mr-1"><InfoFilled /></el-icon>
          重新提交将：
          <ul class="list-disc ml-4 mt-1">
            <li>重置所有任务状态为待处理</li>
            <li>清空之前的错误信息和重试次数</li>
            <li>使用新的评论信息重新发起请求</li>
          </ul>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitEdit"
              :loading="submitLoading"
          >
            确定{{ editForm.resubmit ? '并重新提交' : '' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除进度对话框 -->
    <el-dialog
        v-model="deleteProgressVisible"
        title="删除进度"
        width="400px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
    >
      <div class="text-center">
        <p class="mb-4">正在删除选中的批次...</p>
        <el-progress
            :percentage="deleteProgress"
            :status="deleteProgress >= 100 ? 'success' : ''"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { format } from 'date-fns'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useCommentsStore } from '@/stores/adminComment'
import {ArrowDown, InfoFilled, More, QuestionFilled} from "@element-plus/icons-vue";
import { utils, writeFile } from 'xlsx';

const router = useRouter()
const commentsStore = useCommentsStore()
const tableRef = ref(null)
const formRef = ref(null)
const editDialogVisible = ref(false)
const deleteProgressVisible = ref(false)
const deleteProgress = ref(0)
const submitLoading = ref(false)
const editForm = ref({
  nickname: '',
  email: '',
  websiteUrl: '',
  commentContent: '',
  resubmit: false  // 添加重新提交选项
})
const currentEditBatchNos = ref([])

const isMultiple = computed(() => currentEditBatchNos.value.length > 1)

const loading = ref(false)
const batchList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedBatchNos = ref([])

// 表单验证规则
const formRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  websiteUrl: [
    {
      required: true,
      message: '请输入网站地址',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]{2,63}(\/[\w-]*)*$/;
        if (!value) {
          callback(new Error('请输入网站地址'));
        } else if (!urlRegex.test(value)) {
          callback(new Error('请输入正确的网站地址'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ]
}

// 导出处理
const handleExport = async () => {
  try {
    if (!selectedBatchNos.value.length) {
      ElMessage.warning('请选择要导出的批次')
      return
    }

    loading.value = true
    // 获取选中批次的评论链接
    const data = await commentsStore.getSuccessCommentUrls(selectedBatchNos.value)

    if (!data || !data.length) {
      ElMessage.warning('所选批次没有可导出的评论链接')
      return
    }

    // 准备Excel数据
    const exportData = data.map(item => ({
      '批次号': item.batchNo,
      '目标网址': item.targetUrl,
      '评论链接': item.newCommentUrl
    }))

    // 创建工作簿
    const wb = utils.book_new()
    const ws = utils.json_to_sheet(exportData)

    // 设置列宽
    ws['!cols'] = [
      { wch: 20 },  // 批次号
      { wch: 50 },  // 目标网址
      { wch: 50 }   // 评论链接
    ]

    // 添加工作表到工作簿
    utils.book_append_sheet(wb, ws, 'Comments')

    // 导出文件
    const fileName = selectedBatchNos.value.length === 1
        ? `评论链接_${selectedBatchNos.value[0]}.xlsx`
        : `评论链接_${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`

    writeFile(wb, fileName)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('Failed to export:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 选择操作处理
const handleSelectionCommand = (command) => {
  switch (command) {
    case 'selectAll':
      tableRef.value.toggleAllSelection()
      break
    case 'unselectAll':
      tableRef.value.clearSelection()
      break
    case 'invertSelection':
      const allRows = batchList.value
      const selectedRows = tableRef.value.getSelectionRows()
      allRows.forEach(row => {
        tableRef.value.toggleRowSelection(row, !selectedRows.includes(row))
      })
      break
  }
}

// 编辑处理
const handleEdit = (row, isBatch = false) => {
  currentEditBatchNos.value = isBatch ? selectedBatchNos.value : [row.batchNo]
  if (!isBatch) {
    // 单个编辑时填充表单
    editForm.value = { ...row }
  } else {
    // 批量编辑时清空表单
    editForm.value = {
      nickname: '',
      email: '',
      websiteUrl: '',
      commentContent: '',
      resubmit: false
    }
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    await formRef.value.validate()

    submitLoading.value = true

    // 如果是重新提交，添加确认提示
    if (editForm.value.resubmit) {
      const count = currentEditBatchNos.value.length
      await ElMessageBox.confirm(
          `您选择了${count}个批次进行修改并重新提交评论，此操作将重置所有任务状态并重新发起评论请求，是否继续？`,
          '确认重新提交',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )
    }

    await commentsStore.updateBatchInfo(
        currentEditBatchNos.value,
        editForm.value
    )

    ElMessage.success(
        editForm.value.resubmit
            ? '修改成功，评论任务已重新提交'
            : '修改成功'
    )

    editDialogVisible.value = false
    await fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to update batch info:', error)
      ElMessage.error('修改失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除处理
const handleDelete = async (row, isBatch = false) => {
  const batchNos = isBatch ? selectedBatchNos.value : [row.batchNo]
  const message = isBatch
      ? `此操作将永久删除选中的 ${batchNos.length} 个批次及其所有任务，是否继续？`
      : '此操作将永久删除该批次及其所有任务，是否继续？'

  try {
    await ElMessageBox.confirm(message, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    })

    deleteProgressVisible.value = true
    deleteProgress.value = 0

    // 分批删除并更新进度
    const batchSize = 5
    for (let i = 0; i < batchNos.length; i += batchSize) {
      const currentBatch = batchNos.slice(i, i + batchSize)
      await commentsStore.deleteBatches(currentBatch)
      deleteProgress.value = Math.round(((i + batchSize) / batchNos.length) * 100)
    }

    setTimeout(() => {
      deleteProgressVisible.value = false
      ElMessage.success('删除成功')
      tableRef.value.clearSelection()
      fetchData()
    }, 500)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete batches:', error)
      ElMessage.error('删除失败')
      deleteProgressVisible.value = false
    }
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedBatchNos.value = selection.map(item => item.batchNo)
}

// 获取表格序号
const getTableIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1
}

// 计算进度百分比
const calculateProgress = (row) => {
  if (!row.totalCount) return 0
  return Math.round(((row.successCount + row.failureCount) / row.totalCount) * 100)
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'info',
    'PROCESSING': 'primary',
    'COMPLETED': 'success',
    'FAILED': 'danger',
    'PARTIALLY_COMPLETED': 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取进度条状态
const getProgressStatus = (status) => {
  const statusMap = {
    'COMPLETED': 'success',
    'FAILED': 'exception',
    'PARTIALLY_COMPLETED': 'warning'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '等待中',
    'PROCESSING': '执行中',
    'COMPLETED': '已完成',
    'FAILED': '执行失败',
    'PARTIALLY_COMPLETED': '部分完成'
  }
  return textMap[status] || status
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '--'
  return format(new Date(time), 'yyyy年MM月dd日 HH:mm:ss')
}

// 查看详情
const viewDetails = (batchNo) => {
  router.push(`/admin-comment/listDetail/${batchNo}`)
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const response = await commentsStore.getBatchList({
      current: currentPage.value,
      pageSize: pageSize.value
    })
    batchList.value = response.records
    total.value = response.total
  } catch (error) {
    console.error('Failed to fetch batch list:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const refresh = async (row,isBatch = false) => {
  try {
    const batchNos = isBatch ? selectedBatchNos.value : [row.batchNo]
    loading.value = true
    await commentsStore.dataRefresh(batchNos);
    await fetchData()
  }catch(error) {
    ElMessage.error('刷新出错')
  }finally {
    loading.value = false
  }
}

onMounted(async () => {
  await fetchData()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.batch-list {
  max-width: 1400px;
  margin: 24px auto;
  padding: 0 16px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
}

:deep(.el-statistic) {
  --el-statistic-content-font-size: 14px;
  --el-statistic-title-font-size: 12px;
}

:deep(.el-progress) {
  margin-top: 0;
  margin-bottom: 0;
}

.batch-list {
  max-width: 1400px;
  margin: 24px auto;
  padding: 0 16px;
}

:deep(.el-dropdown-menu__item.danger) {
  color: var(--el-color-danger);
}
</style>